﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using FFSupplier.Common.TKCommon;

namespace FFSupplier.Common.Helper
{
    public class CRMHelper
    {
        public CRMHelper()
        {
            httpClient = ConnectToCRM();
        }
        public CRMHelper(string crmApiUser, string crmApiPassword)
        {
            httpClient = ConnectToCRM( crmApiUser,  crmApiPassword);
        }
        ~CRMHelper()
        {
            httpClient.Dispose();
        }
        public HttpClient httpClient = null;
        public string accesstoken = "";
        /// <summary>
        /// 链接crm
        /// </summary>
        private HttpClient ConnectToCRM()
        {
            HttpClient httpClient = new HttpClient();

            if (APConfig.crmApiUrlBase.Contains("https"))
            {
                httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/api/data/v9.0/");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                var tokencontent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("client_id","ea1d02b9-3cbb-4bc7-b109-31ac1805c57f"),
                new KeyValuePair<string,string>("client_secret","OWRfTWozPgwPEyIPQkr2ErYPh1bJ_zrIUfrHSAZl"),
                new KeyValuePair<string,string>("resource","https://tcsw.tcsw.com.cn/api/data/v9.0/"),
                new KeyValuePair<string,string>("username",@"tcsw\crmadmin"),
                new KeyValuePair<string,string>("password","Teconphi@123"),
                new KeyValuePair<string,string>("grant_type","password"),
                         });
                var res = httpClient.PostAsync("https://adfs.tcsw.com.cn/adfs/oauth2/token", tokencontent);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accesstoken);
            }
            else
            {
                httpClient = new HttpClient(new HttpClientHandler()
                {
                    Credentials = new NetworkCredential(APConfig.crmApiUser, APConfig.crmApiPassword, APConfig.crmApiDomain)
                });
                //Specify the Web API address of the service and the period of time each request 
                // has to execute.
                httpClient.BaseAddress = new Uri(APConfig.crmApiUrlBase);
                httpClient.Timeout = new TimeSpan(0, 2, 0);  //2 minutes
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                //  httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                // httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
             //   httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/api/data/v9.0/");
                //   httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", "b59f39a6-03b9-e911-84db-e94e2aa2ba42");
                //Send the WhoAmI request to the Web API using a GET request. 
            }
            return httpClient;
        }
        /// <summary>
        /// 链接crm
        /// </summary>
        private HttpClient ConnectToCRM(string crmApiUser,string crmApiPassword)
        {

            HttpClient httpClient = new HttpClient();

            if (APConfig.crmApiUrlBase.Contains("https"))
            {
                httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/api/data/v9.0/");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                var tokencontent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("client_id","ea1d02b9-3cbb-4bc7-b109-31ac1805c57f"),
                new KeyValuePair<string,string>("client_secret","OWRfTWozPgwPEyIPQkr2ErYPh1bJ_zrIUfrHSAZl"),
                new KeyValuePair<string,string>("resource","https://tcsw.tcsw.com.cn/api/data/v9.0/"),
                new KeyValuePair<string,string>("username",@"tcsw\"+crmApiUser),
                new KeyValuePair<string,string>("password",crmApiPassword),
                new KeyValuePair<string,string>("grant_type","password"),
                         });
                var res = httpClient.PostAsync("https://adfs.tcsw.com.cn/adfs/oauth2/token", tokencontent);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accesstoken);
            }
            else
            {
                httpClient = new HttpClient(new HttpClientHandler()
                {
                    Credentials = new NetworkCredential(crmApiUser, crmApiPassword, APConfig.crmApiDomain)
                });
                //Specify the Web API address of the service and the period of time each request 
                // has to execute.
                httpClient.BaseAddress = new Uri(APConfig.crmApiUrlBase);
                httpClient.Timeout = new TimeSpan(0, 2, 0);  //2 minutes
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                //  httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                // httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
                //   httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/api/data/v9.0/");
                //   httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", "b59f39a6-03b9-e911-84db-e94e2aa2ba42");
                //Send the WhoAmI request to the Web API using a GET request. 
            }
            return httpClient; 
        }
        public string GetPageRecord(string url, int count)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(APConfig.crmApiUrlBase + url);
            req.Credentials = new NetworkCredential(APConfig.crmApiUser, APConfig.crmApiPassword, APConfig.crmApiDomain);
            req.Method = "Get";
            req.Accept = "application/json";
            req.ContentType = "application/json; charset=utf-8";
            req.Headers.Set("OData-MaxVersion", "4.0");
            req.Headers.Set("OData-Version", "4.0");
            req.Headers.Set("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue, odata.maxpagesize = " + count);
            using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
            {
                StreamReader read = new StreamReader(res.GetResponseStream());
                result = read.ReadToEnd();
            }
            return result;
        }

        public string GetRecordsBySpecifiedPageIndex(string url)
        {
            string ret = "";


            return ret;
        }
        public async Task<string> SendCrmRequestAsync(
           HttpMethod method, string query)
        {
            string result = "";
            HttpRequestMessage request = new HttpRequestMessage(method, query);
            request.Headers.Add("Prefer",
                "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
           // request.Headers.Add("Authorization", "Bearer " + accesstoken);
            HttpResponseMessage response = await httpClient.SendAsync(request);
                if (response.StatusCode == HttpStatusCode.OK) //200
                {
               result = await response.Content.ReadAsStringAsync();
               
                }
               
            return result;
        }

        public  string SendCrmRequestsync(
         HttpMethod method, string query)
        {
            string result = "";
            HttpRequestMessage request = new HttpRequestMessage(method, query);
            request.Headers.Add("Prefer",
                "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
            // request.Headers.Add("Authorization", "Bearer " + accesstoken);
            HttpResponseMessage response =   httpClient.SendAsync(request).Result;
            if (response.StatusCode == HttpStatusCode.OK) //200
            {
                result = response.Content.ReadAsStringAsync().Result;

            }

            return result;
        }

        public async Task<bool> CreatToCrm(string updateStr, string entityName
            )
        {
            bool ret = true;
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), APConfig.crmApiUrlBase + entityName);
            request.Content = new StringContent(updateStr, Encoding.UTF8, "application/json");
            // request.Headers.Add("If-Match", "*");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                ret = false;
            }

            return ret;
        }
        public async Task<bool> PostToCrm(string updateStr, string entityName
          )
        {
         //   LoggerHelper.Instance.Error("PostToCrm1！", new Exception(entityName));
            bool ret = true;
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), APConfig.crmApiUrlBase + entityName);
            request.Content = new StringContent(updateStr, Encoding.UTF8, "application/json"); 
            // request.Headers.Add("If-Match", "*");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                ret = false;
                var exp = new CrmHttpResponseException(response.Content);
                LoggerHelper.Instance.Error("PostToCrm！", exp);
                throw new Exception(exp.Message);
            }
            return ret;
        }
        public async Task<bool> PostToCrm(string updateStr, string entityName,string user  )
        {
            bool ret = true;
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), APConfig.crmApiUrlBase + entityName);
            request.Content = new StringContent(updateStr, Encoding.UTF8, "application/json");
            request.Headers.Add("MSCRMCallerID", user);
            // request.Headers.Add("If-Match", "*");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                ret = false;
                var exp = new CrmHttpResponseException(response.Content);
                LoggerHelper.Instance.Error("PostToCrm！", exp);
                throw new Exception(exp.Message);
            }
            return ret;
        }
        public async Task<string> createRecord(string updateStr, string entityName)
        {
            string id = "";
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("POST"), APConfig.crmApiUrlBase + entityName);
            request.Content = new StringContent(updateStr, Encoding.UTF8, "application/json");
            // request.Headers.Add("If-Match", "*");
            // request.Headers.Add("Prefer", "return=representation");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                var exception = new CrmHttpResponseException(response.Content);
                throw new HttpException(exception.ToString());
            }
            string responseUrl = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
            id = Regex.Replace(responseUrl, @"(.*\()(.*)(\).*)", "$2");
            return id;
        }

        public    string createRecordSync(string updateStr, string entityName)
        {
            string id = "";
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("POST"), APConfig.crmApiUrlBase + entityName);
            request.Content = new StringContent(updateStr, Encoding.UTF8, "application/json");
            // request.Headers.Add("If-Match", "*");
            // request.Headers.Add("Prefer", "return=representation");
            HttpResponseMessage response =   httpClient.SendAsync(request).Result;
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                var exception = new CrmHttpResponseException(response.Content);
                throw new HttpException(exception.ToString());
            }
            string responseUrl = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
            id = Regex.Replace(responseUrl, @"(.*\()(.*)(\).*)", "$2");
            return id;
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="updateStr"></param>
        /// <param name="entityName"></param>
        public async Task<string> deleteRecord(string id, string entityName)
        {
            string ret = "";
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("DELETE"), APConfig.crmApiUrlBase + entityName + "(" + id + ")");
            // request.Headers.Add("If-Match", "*");
            // request.Headers.Add("Prefer", "return=representation");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                ret = new CrmHttpResponseException(response.Content).ToString();
                // throw new HttpException(exception.ToString());
            }
            return ret;
        }
        public async void SentToCRM(string entityname, string key, string updateStr)
        {
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), APConfig.crmApiUrlBase + entityname + key);
            request.Content = new StringContent(updateStr, Encoding.UTF8, "application/json");
            HttpResponseMessage response = httpClient.SendAsync(request).Result;

        }

        public async Task<string> CallAction(JObject customerParam, string acitonName)
        {
            string ret = "";
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, acitonName);
            request.Content = new StringContent(customerParam.ToString(), Encoding.UTF8, "application/json");
            HttpResponseMessage response = httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).Result;
            if (!response.IsSuccessStatusCode)
            {
                var ex = new CrmHttpResponseException(response.Content);
                throw ex;
            }
            ret = await response.Content.ReadAsStringAsync();
            return ret;
        }
    }
 
    public static class APIHelper
    {
        /// <summary>
        /// 依据键获取请求头中值数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetHeader(this HttpRequestMessage request, string key)
        {
            IEnumerable<string> keys = null;
            if (!request.Headers.TryGetValues(key, out keys))
                return null;

            return keys.First();
        }



    }
     
}
